package com.peng.herostory;

import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GameMsgDecoder extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof BinaryWebSocketFrame)) {
            return;
        }
        BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
        ByteBuf byteBuf = frame.content();
        short dataLength = byteBuf.readShort();
        short dataNo = byteBuf.readShort();


        Message.Builder msgBuilder = GameMsgRecognizer.getMsgBuilderByCode(dataNo);
        if (msgBuilder == null) {
            return;
        }
        byte[] content = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(content);

        msgBuilder.clear();
        msgBuilder.mergeFrom(content);
        Message message = msgBuilder.build();
//        switch (dataNo) {
//            case GameMsgProtocol.MsgCode.USER_ENTRY_CMD_VALUE:
//                cmd = GameMsgProtocol.UserEntryCmd.parseFrom(content);
//                break;
//            case GameMsgProtocol.MsgCode.WHO_ELSE_IS_HERE_CMD_VALUE:
//                cmd = GameMsgProtocol.WhoElseIsHereCmd.parseFrom(content);
//                break;
//            case GameMsgProtocol.MsgCode.USER_MOVE_TO_CMD_VALUE:
//                cmd = GameMsgProtocol.UserMoveToCmd.parseFrom(content);
//                break;
//
//        }

        if (null != message) {
            ctx.fireChannelRead(message);
        }


    }
}
